/**
 * @ReplyAccessTcpRequestHandler.java  COPYRIGHT xiaojian
 * 
 * Created on 2017年7月19日 下午5:51:35
 */
package xj.toolkit.access.busi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.ChannelHandlerContext;
import xj.toolkit.netty.handler.TcpRequestHandler;
import xj.toolkit.util.MutablePropertyable;
import xj.toolkit.access.AccessHeader;
import xj.toolkit.access.msg.AccessAckMessage;
import xj.toolkit.access.msg.AccessSynMessage;

/**
 * 等Access的接入请求，如果有的话，则回应实例号以及模块号。
 * 
 * @author <a href="mailto:cxj2000@gmail.com">xiaojian.cao</a>
 *
 */
public class ReplyAccessTcpRequestHandler extends TcpRequestHandler {
	
	private static final Logger logger = LoggerFactory.getLogger(ReplyAccessTcpRequestHandler.class);

	private short moduleId;
	
	private short instanceId;
	
	public short getModuleId() {
		return moduleId;
	}

	public void setModuleId(short moduleId) {
		this.moduleId = moduleId;
	}

	public short getInstanceId() {
		return instanceId;
	}

	public void setInstanceId(short instanceId) {
		this.instanceId = instanceId;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.debug("messageReceived {}", msg);
		
		if (msg instanceof AccessSynMessage) {
			AccessSynMessage accessSynMessage = (AccessSynMessage) msg;
			
			AccessAckMessage ackMsg = new AccessAckMessage();
			
			AccessHeader header = new AccessHeader();
			header.setSourceInstanceId(instanceId);
			header.setSourceModuleId(moduleId);
			header.setTargetInstanceId(accessSynMessage.getAccessHeader().getSourceInstanceId());
			header.setTargetModuleId(accessSynMessage.getAccessHeader().getSourceModuleId());
			
			ackMsg.setAccessHeader(header);
			ackMsg.setProperty(AccessHeader.KEY, header);
			
			ackMsg.getCommonHeader().setFirstTransaction(accessSynMessage.getCommonHeader().getFirstTransaction());
			ackMsg.getCommonHeader().setSecondTransaction(accessSynMessage.getCommonHeader().getSecondTransaction());
			ackMsg.getCommonHeader().setMessageLength(AccessHeader.HEADER_LENGTH);
			
			ctx.channel().writeAndFlush(ackMsg);
			return;
		}
		
		MutablePropertyable mutablePropertyable = (MutablePropertyable) msg;
		AccessHeader accessHeader = (AccessHeader) mutablePropertyable.getProperty(AccessHeader.KEY);
		if (accessHeader == null) {
			throw new Exception("Cannot found accessheader, msg[" + msg + "].");
		}
		
		accessHeader.setTargetInstanceId(accessHeader.getSourceInstanceId());
		accessHeader.setTargetModuleId(accessHeader.getSourceInstanceId());
		accessHeader.setSourceInstanceId(instanceId);
		accessHeader.setSourceModuleId(moduleId);
		
		super.channelRead(ctx, msg);
	}
}
